import { useReactive } from "ahooks";
import { useEffect } from "react";

const useAreaCode = () => {
    const state = useReactive({
        loading: false,
        areas: [],
    });

    const loadAreaData = (selectedOptions) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;

        let children = globalAreaCode[targetOption.id];
        if (children && children.length > 0) {
            if (targetOption.level < 3) {
                targetOption.children = children.map((item) => ({ ...item, isLeaf: false, level: targetOption.level + 1 }));
            } else {
                targetOption.children = children.map((item) => ({ ...item, isLeaf: true, level: targetOption.level + 1 }));
            }
            targetOption.loading = false;
            state.areas = [...state.areas];
        } else {
            targetOption.isLeaf = true;
            targetOption.loading = false;
            state.areas = [...state.areas];
        }
    };

    useEffect(() => {
        let areasCache = globalAreaCode["0"].map((item) => ({ ...item, isLeaf: false, level: 1 }));
        state.areas = areasCache;
    }, []);

    return { ...state, loadAreaData };
};

export default useAreaCode;
